<template>
  <a-upload
    class="upload-wrap"
    :action="url"
    :headers="headers"
    :multiple="true"
    :file-list="fileList"
    list-type="picture"
    :beforeUpload="handlerBeforeUpload"
    @preview="handlePreview"
    @change="handleChange"
  >
    <a-button class="dg-base-btn">上传</a-button>
    <PreviewMediaModal ref="preViewModal"></PreviewMediaModal>
  </a-upload>
</template>

<script>
const baseUrl = process.env.VUE_APP_BASE_URL
import { getStorage } from '@/utils/index'
import PreviewMediaModal from '@/components/common/PreviewMediaModal'

export default {
  props: {
    instance: Object, // 实例配置
  },
  data() {
    return {
      headers: {}, // 请求头的参数
      uploadTypeMap:
        'bmp,jpg , png , tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF,webp,avif,apng,jpeg', // 请求的限制条件
      showUploadList: {
        showPreviewIcon: true,
        showRemoveIcon: true,
      },
      url: baseUrl + '/system/file/pop',
      fileList: [], // 上传结果
    }
  },
  components: {
    PreviewMediaModal,
  },

  watch: {
    instance: {
      handler(nVal) {
        const defaultV = nVal.defaultValue
        if (defaultV && this.fileList.length === 0) {
          this.fileList = defaultV.reduce((pre, cur, index) => {
            const { fileName, filePath, id } = cur
            if (!fileName) return
            pre.push({
              name: fileName,
              uid: index,
              id,
              url: filePath,
            })
            return pre
          }, [])
        }
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    const token = `${getStorage('token', 0)}`
    this.headers = {
      Authorization: token,
    }
  },
  methods: {
    handlerBeforeUpload(file) {
      const { name } = file
      const type = name.split('.').slice(-1)
      if (this.fileList.length >= 1) {
        this.$apiStatusHandler(99, '图片上传不能超过1个')
        return Promise.reject()
      }
      if (this.uploadTypeMap.indexOf(type) === -1) {
        this.$apiStatusHandler(99, '上传的附件类型不符合要求')
        return Promise.reject()
      }
    },
    // 打开模态框（图片预览）
    async handlePreview(file) {
      const url = file.url || file.response.data[0].filePath
      this.$refs.preViewModal.showPreViewMedia(url)
    },
    handleChange(info) {
      const { fileList } = info
      this.fileList = fileList
      this.$emit('change', fileList)
    },
  },
}
</script>

<style scoped lang="scss">
::v-deep .ant-upload-list {
  //营业执照图片过长
  width: 341px !important;
}
</style>
